package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    XcMenuMapper xcMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try {
            //将认证参数转为AuthParamsDto类型
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }

        //认证类型
        String authType=authParamsDto.getAuthType();
        //根据认证类型从spring容器中取出指定的bean
        String beanName=authType+"_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        //调用统一的excute方法完成认证
        XcUserExt execute = authService.execute(authParamsDto);
        //封装xcUserExt用户信息为UserDetails
        UserDetails userDetails = getUserPrincipal(execute);
        return userDetails;
    }

    public UserDetails getUserPrincipal(XcUserExt xcUser){
        String password=xcUser.getPassword();
        String[] authorities={"test"};
        //根据id查询用户用户权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUser.getId());
        if (xcMenus.size()>0){
            List<String> permissions=new ArrayList<>();
            xcMenus.forEach(m->{
                //拿到用户拥有的权限标识符
                permissions.add(m.getCode());
            });
            //将permissions转成数组
            authorities=permissions.toArray(new String[0]);
        }
        xcUser.setPassword(null);
        String userJson=JSON.toJSONString(xcUser);
        UserDetails userDetails=User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }
}
